package servlet;

import entity.User;
import service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserService userService;

    @Override
    public void init() throws ServletException {
        userService = new UserService();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phone = request.getParameter("phone");
        Integer gender = Integer.valueOf(request.getParameter("gender"));
        Integer userType =  Integer.valueOf(request.getParameter("userType"));

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setPhone(phone);
        user.setGender(gender);
        user.setUserType(userType);

        boolean result = userService.register(user);
        if (result) {
            response.sendRedirect("login.jsp");
        } else {
            request.setAttribute("errorMessage", "用户名已存在");
            request.getRequestDispatcher("register.jsp").forward(request, response);
        }
    }
}
